package com.showwindow.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.market.category.dao.CategoryDao;
import com.market.category.domain.CategoryCommand;
import com.market.product.dao.ProductDao;
import com.market.product.domain.ProductCommand;
import com.market.util.PagingUtil;

@Controller
public class ShowwindowController {
	private int pageSize = 6;
	private int blockCount = 2;
	
	@Autowired
	CategoryDao categoryDao;
	@Autowired
	ProductDao productDao;
	
	@RequestMapping("/showwindow.do")
	public ModelAndView process(@RequestParam(value="pageNum",defaultValue="1")int currentPage,
			@RequestParam(value="market",defaultValue="none")String market,
			@RequestParam(value="category",defaultValue="none")String category) {
		String pagingHtml = "";
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("keyWord", market);
		map.put("keyWord2", category);
		map.put("show", "y");
		
		int count = 0;
		
		if(!market.equals("none") && !category.equals("none")){
			count = productDao.getRowCount(map);
			System.out.println(count);
		}		
		
		PagingUtil page = new PagingUtil(market, category,
				currentPage, count, pageSize, blockCount, "showwindow.do");
		pagingHtml = page.getPagingHtml().toString();
		
		map.put("start", page.getStartCount());
		map.put("end", page.getEndCount());
				
		List<CategoryCommand> menuList = null;
		if(!market.equals("none")){
			menuList = categoryDao.list(map);			
		}			
		
		List<ProductCommand> productList = null;
		if(!category.equals("none")){
			productList = productDao.list(map);
			
			for(ProductCommand pc : productList){
				String tempImage[] = pc.getImage().split("&");
				pc.setImage(tempImage[0]);
			}
		}
		
		if(count < 1){
			productList = Collections.emptyList();
		}
		
		int number = count-(currentPage-1)*pageSize;		
		
		System.out.println(productList.size());
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("showwindow");
		mav.addObject("market", market);
		mav.addObject("menu", menuList);		
		mav.addObject("category", category);
		mav.addObject("productList",productList);
		
		mav.addObject("count", count);
		mav.addObject("pagingHtml", pagingHtml);
		mav.addObject("number", number);
		mav.addObject("pageNum",currentPage);
		return mav;
	}	
}
